﻿<template>
  <!-- 任务列表 -->
  <el-row style="margin: 10px">
    <el-col :span="12">
      <el-button type="primary" @click="handlerAdd">新增</el-button>
      <el-button :disabled="isCanDelete" type="danger" @click="handlerDeletes">批量删除</el-button>
    </el-col>
  </el-row>
  <el-row style="margin: 10px">
    <el-col :span="24">
      <el-table
          :data="taskList"
          border
          style="width: 100%; margin-top: 10px;"
          v-loading="tableLoading"
          @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="id" label="ID" min-width="80" fixed="left"/>
        <el-table-column prop="taskCode" label="任务编码" min-width="120" fixed="left"/>
        <el-table-column prop="taskName" label="任务名称" min-width="180"/>
        <el-table-column prop="workstationCode" label="工作站编码" min-width="120"/>
        <el-table-column label="工作站名称" min-width="150">
          <template #default="scope">
            {{ scope.row.workstation?.name || '未分配' }}
          </template>
        </el-table-column>
        <el-table-column prop="scheduleQuantity" label="排产数量" min-width="100"/>
        <el-table-column prop="startProduceTime" label="开始时间" min-width="160"/>
        <el-table-column prop="produceDuration" label="生产时长(小时)" min-width="140"/>
        <el-table-column prop="expectedFinishTime" label="完成时间" min-width="160"/>
        <el-table-column
            prop="ganttColor"
            label="甘特图颜色" min-width="120">
          <template v-slot="scope">
            <el-color-picker v-model="scope.row.ganttColor" disabled />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>

  <!-- 新增/编辑 弹窗 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" destroy-on-close>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
      <!-- 按照指定顺序：任务编码，任务名称，工作站编码，甘特图颜色，排产数量，开始时间，生产时长，完成时间 -->
      <el-form-item label="任务编码" prop="taskCode">
        <el-input v-model="form.taskCode" placeholder="请输入任务编码" />
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input v-model="form.taskName" placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="工作站编码" prop="workstationCode">
        <el-input v-model="form.workstationCode" placeholder="请输入工作站编码">
          <template #append>
            <el-button @click="workstationPickerVisible = true">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="甘特图颜色" prop="ganttColor">
        <el-color-picker v-model="form.ganttColor" />
      </el-form-item>
      <el-form-item label="排产数量" prop="scheduleQuantity">
        <el-input v-model.number="form.scheduleQuantity" placeholder="请输入排产数量" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startProduceTime">
        <el-date-picker
          v-model="form.startProduceTime"
          type="datetime"
          placeholder="选择开始时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="生产时长(小时)" prop="produceDuration">
        <el-input v-model.number="form.produceDuration" placeholder="请输入生产时长(小时)" />
      </el-form-item>
      <el-form-item label="完成时间" prop="expectedFinishTime">
        <el-date-picker
          v-model="form.expectedFinishTime"
          type="datetime"
          placeholder="选择完成时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="onSubmit">保存</el-button>
    </template>

    <!-- 弹窗末尾挂载：工作站选择组件，仅显示当前工序的工作站 -->
    <workstation-list
      v-model="workstationPickerVisible"
      :default-process-id="form.processId || props.processId"
      :enforce-process-only="true"
      @confirm="onPickWorkstation"
    />
  </el-dialog>
</template>

<script setup>
import {onMounted, ref, watch, computed} from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
//导入任务列表的API
import {
  getProschedueTaskListByWorkflowId,
  addProschedueTask,
  updateProschedueTask,
  deleteProschedueTask,
} from "@/api/proschedue_task.js"
import WorkstationList from './workstation-list.vue'

const props = defineProps({
  workflowId: {
    type: Number
  },
  processId: {  // 工序ID
    type: Number
  },
  taskList: { // 接收父组件传递的过滤后任务列表
    type: Array,
    default: () => []
  }
})

const taskList = ref([])
const tableLoading = ref(false)
const selectedRows = ref([])
const isCanDelete = computed(() => selectedRows.value.length === 0)

// 工作站选择弹窗控制与回调
const workstationPickerVisible = ref(false)
const onPickWorkstation = (row) => {
  // 仅回填编码，如需名称也可一起保存
  form.value.workstationCode = row.code
}

// 兼容不同返回结构
const normalizeList = (res) => {
  const data = res?.data ?? res;
  let list = [];
  if (Array.isArray(data)) list = data;
  else if (Array.isArray(data?.list)) list = data.list;
  else if (Array.isArray(data?.records)) list = data.records;
  else if (Array.isArray(res?.list)) list = res.list;
  else if (Array.isArray(res?.records)) list = res.records;
  if (list.length === 0 && data && typeof data === 'object') {
    for (const k of Object.keys(data)) { if (Array.isArray(data[k])) { list = data[k]; break; } }
  }
  return list;
}

// 表单
const dialogVisible = ref(false)
const dialogTitle = ref('新增任务')
const submitLoading = ref(false)
const formRef = ref()
const form = ref({
  id: undefined,
  workflowId: undefined,
  processId: undefined,
  taskCode: '',
  taskName: '',
  workstationCode: '',
  ganttColor: '#409EFF',
  scheduleQuantity: undefined,
  startProduceTime: '',
  produceDuration: undefined,
  expectedFinishTime: '',
})
const rules = {
  taskCode: [{ required: true, message: '请输入任务编码', trigger: 'blur' }],
  taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  workstationCode: [{ required: true, message: '请输入工作站编码', trigger: 'blur' }],
  ganttColor: [{ required: true, message: '请选择甘特图颜色', trigger: 'change' }],
  scheduleQuantity: [{ required: true, message: '请输入排产数量', trigger: 'blur' }],
  startProduceTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  expectedFinishTime: [{ required: true, message: '请选择完成时间', trigger: 'change' }],
  produceDuration: [{ required: true, message: '请输入生产时长', trigger: 'blur' }],
}

const resetForm = () => {
  form.value = {
    id: undefined,
    workflowId: props.workflowId,
    processId: props.processId,
    taskCode: '',
    taskName: '',
    workstationCode: '',
    ganttColor: '#409EFF',
    scheduleQuantity: undefined,
    startProduceTime: '',
    produceDuration: undefined,
    expectedFinishTime: '',
  }
  formRef.value && formRef.value.clearValidate()
}

const refreshList = () => {
  if (!props.workflowId) return;
  tableLoading.value = true
  getProschedueTaskListByWorkflowId(props.workflowId)
    .then(res => {
      const all = normalizeList(res)
      taskList.value = (all || []).filter(it => Number(it?.processId) === Number(props.processId))
    })
    .finally(() => { tableLoading.value = false })
}

const handlerAdd = () => {
  dialogTitle.value = '新增任务'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑任务'
  form.value = {
    id: row.id,
    workflowId: row.workflowId ?? props.workflowId,
    processId: row.processId ?? props.processId,
    taskCode: row.taskCode,
    taskName: row.taskName,
    workstationCode: row.workstationCode,
    ganttColor: row.ganttColor || '#409EFF',
    scheduleQuantity: row.scheduleQuantity,
    startProduceTime: row.startProduceTime,
    produceDuration: row.produceDuration,
    expectedFinishTime: row.expectedFinishTime,
  }
  dialogVisible.value = true
}

const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      const payload = { ...form.value }
      payload.workflowId = payload.workflowId ?? props.workflowId
      payload.processId = payload.processId ?? props.processId
      if (payload.id) {
        await updateProschedueTask(payload)
        ElMessage.success('更新成功')
      } else {
        await addProschedueTask(payload)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      refreshList()
    } catch (e) {
      ElMessage.error('保存失败')
    } finally {
      submitLoading.value = false
    }
  })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确认删除任务【${row.taskName || row.taskCode || row.id}】吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    await deleteProschedueTask(row.id)
    ElMessage.success('删除成功')
    refreshList()
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('删除失败')
  }
}

const handlerDeletes = async () => {
  if (selectedRows.value.length === 0) return
  const ids = selectedRows.value.map(it => it.id)
  try {
    await ElMessageBox.confirm(`确认逐条删除选中的 ${ids.length} 条任务吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    tableLoading.value = true
    for (const id of ids) {
      await deleteProschedueTask(id)
    }
    ElMessage.success(`批量删除成功，共删除 ${ids.length} 条`)
    refreshList()
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('批量删除失败')
  } finally {
    tableLoading.value = false
  }
}

const onSelectionChange = (rows) => {
  selectedRows.value = rows || []
}

// 监听注入的任务列表变化
watch(() => props.taskList, (newList) => {
  taskList.value = newList || [];
}, { immediate: true });

onMounted(()=>{
  // 初始使用父组件传入的数据；增删改后刷新接口数据
})
</script>
<style scoped>

</style>
